
<?php
require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_CATEGORIES;
require_once LIBRARIES_ENTITIES_LOGO;
require_once LIBRARIES_ENTITIES_USERS;
require_once LIBRARIES_ENTITIES_MENUTYPES;
require_once LIBRARIES_ENTITIES_NEWS_LETTER;


require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

    class DanhkydanhmuctinController
    {

        public function invoke()
        {
        	 // function list
        $groupFunctions = $_SESSION['groupFunctions']; 

        // directory path
        $dir = dirname(__FILE__);

        $view = '';
        if (isset($_GET['view'])) {
            $view = $_GET['view'];
        }

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }



        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }


        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }


        switch ($action) {
             case "publish":
                    $values = $_POST["cid"];
                    $result = $this->phanphatbantin($values, true);
                    if ($result == OK) {
                    Utility::messageBox('Phát tin thành công');
                    }else {
                        Utility::messageBox('Phát tin thất bại');
                    }
                    break;
             
               
            case 'removechuyenmuc':
                $values = $_POST["cid"];
                $result = $this->delete($values);
                if ($result == OK) {
                    Utility::messageBox('Xóa thành công');
                }else {
                	Utility::messageBox('Dữ liệu này đang được sử dụng trong đánh giá');
                }
                break;
           
           
            
        }






        if ($task == 'view') {

            // check view permission
            if (Utility::checkPermission('view', $groupFunctions, NEWS_LETTER_MANAGEMENT)) {

                $viewFile = $dir . '/views/list.php';
                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check add button
                if (Utility::checkPermission('add', $groupFunctions, NEWS_LETTER_MANAGEMENT)) {
                    $xtemplate->parse('main.add_button');
                }
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, NEWS_LETTER_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }
                // check enable button
                if (Utility::checkPermission('enable', $groupFunctions, NEWS_LETTER_MANAGEMENT)) {
                    $xtemplate->parse('main.enable_button');
                }
                // check disable button
                if (Utility::checkPermission('disable', $groupFunctions, NEWS_LETTER_MANAGEMENT)) {
                    $xtemplate->parse('main.disable_button');
                }


                $indexCheckBox = 1;

                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }


                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;
                // $article = $this->getArticleByAlias($articleAlias);
               $feedbacks = $this->getDangKyNhomTin();

                $pager = PagerBackEnd::getPagerData(count($feedbacks), $rowToView, $rurrentPage);


                if ($feedbacks != null) {
                    $indexCheckBox=1;
                    foreach ($feedbacks as $feedback) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                          
                                $category=$this->getCategoryByID($feedback->getNL_C_ID());
                                $xtemplate->assign('INDEX', $index);
                                 $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);
                                $xtemplate->assign('NHOMTIN',$category->getTitle());
                                $xtemplate->assign('ID', $feedback->getNL_ID());
                                $xtemplate->assign('EMAIL', $feedback->getNL_GUEST_EMAIL());



                                if($feedback->getNL_REGISTER_DATE()!=null){
                                $createdate1=explode(" ",$feedback->getNL_REGISTER_DATE());
                                $createdate=explode("-",$createdate1[0]);

                                $xtemplate->assign('createdate', $createdate[2].'/'.$createdate[1].'/'.$createdate[0]);
                                 
                                }
                               


                               
   
                                // status
                                if ($feedback->getNL_ACTIVE() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }


                             	$xtemplate->parse('main.feedback');	
                        }
                        $index++;
                        $indexCheckBox++;
                    }
                }

                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->assign('PAGING_HTML', $pager->paging);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        } 
    }
















    private function delete($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                 $Newsletter= new Newsletter();
                $Newsletter->setNL_ID($values[$i]);
                $Newsletter->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $ex) {
            Utility::messageBox('Không thể xóa');
            $db->rollback();
            exit();
        }
    }

   
    

 



 // hàm cập nhật trạng thái bài viết
    private function phanphatbantin($values, $status) {

        try {
            $db = new Database();
            function server_parse($socket, $expected_response)
                    {
                        $server_response = '';
                        while (substr($server_response, 3, 1) != ' ')
                        {
                            if (!($server_response = fgets($socket, 256)))
                                echo 'Lỗi.', __FILE__, __LINE__;
                        }
                     
                        if (!(substr($server_response, 0, 3) == $expected_response))
                            echo 'Lỗi'.$server_response.'"', __FILE__, __LINE__;
                    }
                    function smtp_mail($to, $subject, $message, $headers = '')
                    {
                        $recipients = explode(',', $to);
                        $user = 'quantri.bochihuy@gmail.com';
                        $pass = 'quantri.bochihuy1';
                        $smtp_host = 'ssl://smtp.gmail.com';
                        $smtp_port = 465;
                 
                     
                        if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
                            echo "'Lỗi'$smtp_host' ($errno) ($errstr)", __FILE__, __LINE__;
                     
                        server_parse($socket, '220');
                     
                        fwrite($socket, 'EHLO '.$smtp_host."\r\n");
                        server_parse($socket, '250');
                     
                        fwrite($socket, 'AUTH LOGIN'."\r\n");
                        server_parse($socket, '334');
                     
                        fwrite($socket, base64_encode($user)."\r\n");
                        server_parse($socket, '334');
                     
                        fwrite($socket, base64_encode($pass)."\r\n");
                        server_parse($socket, '235');
                     
                     
                     
                        fwrite($socket, 'MAIL FROM: <example@gmail.com>'."\r\n");
                        server_parse($socket, '250');
                     
                        foreach ($recipients as $email)
                        {
                            fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
                            server_parse($socket, '250');
                        }
                     
                        fwrite($socket, 'DATA'."\r\n");
                        server_parse($socket, '354');
                     
                        fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
                     
                        fwrite($socket, '.'."\r\n");
                        server_parse($socket, '250');
                     
                        fwrite($socket, 'QUIT'."\r\n");
                        fclose($socket);
                     
                        return true;
                    }



            for ($i = 0; $i < count($values); $i++) {
                $dangkytins=$this->getDangKyNhomTinById($values[$i]);

                if($dangkytins!=null){

                    
         
                if($dangkytins->getNL_ACTIVE()==0){


                    $Category=$this->getCategoryByID($dangkytins->getNL_C_ID());
                     $url=$dangkytins->getNL_URL().'./com_content/categories/'.$Category->getAlias().'/'.$Category->getID().'.htm';

                    if($Category!=null){
                         // Send the mail
                        if(smtp_mail($dangkytins->getNL_GUEST_EMAIL(),$Category->getTitle(),$url))
                        {
                           $Newsletter= new Newsletter();
                            $Newsletter->setNL_ID($values[$i]);

                            if ($status == true) {
                                $Newsletter->setNL_ACTIVE(1);
                            } else {
                                $Newsletter->setNL_ACTIVE(0);
                            }
                            $Newsletter->updateNL_ACTIVE($db);
                        }
                    }

                   
                }



                }








                
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }


  private function getDangKyNhomTin() {
        $db = new Database();
        try {
            $Newsletter= new Newsletter();
            $result =  $Newsletter->getList($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

  private function getDangKyNhomTinById($id) {
        $db = new Database();
        try {
            $Newsletter= new Newsletter();
            $Newsletter->setNL_ID($id);
            $result =  $Newsletter->getByID($db);
            $db->submitChanges();
            return $result;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
        }
    }

 private function getCategoryByID($categoryID) {
        try {
            $db = new Database();
            $category = new Categories();
            $category->setID($categoryID);
            $category = $category->getByID($db);
            $db->submitChanges();
            return $category;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }

            
        

    }
?>

